﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace EngineDrawer.Debugging
{
    public class FpsDrawer:DrawableGameComponent
    {
        SpriteFont _font;
        int _totalFrames;
        private float _elapsedTime;
        private int _fps;
        private SpriteBatch _spriteBatch;

        public FpsDrawer(Game game) : base(game)
        {
            DrawOrder = int.MaxValue;
        }    
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _font = Game.Content.Load<SpriteFont>("Fonts\\CounterText");
            base.LoadContent();
        }
        public override void Update(GameTime gameTime)
        {
            _elapsedTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
          
            if (_elapsedTime >= 1000.0f)
            {
                _fps = _totalFrames;
                _totalFrames = 0;
                _elapsedTime = 0;
            }

            base.Update(gameTime);
        }
        public override void Draw(GameTime gameTime)
        {          
            _totalFrames++;            

            _spriteBatch.Begin(SpriteSortMode.Immediate,BlendState.AlphaBlend);
            _spriteBatch.DrawString(_font, string.Format("FPS={0}", _fps),
                                    new Vector2(10.0f, 20.0f), Color.White);
            _spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
